'use client';
import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Input,
  Modal,
  Form,
  Tag,
  Popconfirm,
  message,
  Typography,
  Divider,
  Row,
  Col,
  Progress,
  Space,
  Switch,
  List,
  InputNumber
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { PlusOutlined, EditOutlined, DeleteOutlined, ExclamationCircleOutlined, ArrowUpOutlined, ArrowDownOutlined, SearchOutlined } from '@ant-design/icons';
import { categoryService, type Category as ServiceCategory } from '@/service/category.service';

const { Title, Text, Paragraph } = Typography;
const { Search } = Input;

interface Category extends ServiceCategory {
  sortOrder?: number;
}

const CategoryManagement: React.FC = () => {
  // 状态定义
  const [categories, setCategories] = useState<Category[]>([]);
  const [filteredCategories, setFilteredCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentCategory, setCurrentCategory] = useState<Category | null>(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [form] = Form.useForm();
  const [sorting, setSorting] = useState(false);

  // 加载分类数据
  const fetchCategories = async () => {
    setLoading(true);
    try {
      const response = await categoryService.getAllCategories();
      // 添加排序字段
      const categoriesWithSort = response.map((cat, index) => ({
        ...cat,
        sortOrder: cat.sort || index + 1,
        isActive: cat.isActive 
      }));
      setCategories(categoriesWithSort);
      setFilteredCategories(categoriesWithSort);
    } catch (error) {
      console.error('获取分类列表失败:', error);
      message.error('获取分类列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCategories();
  }, []);

  // 筛选分类
  useEffect(() => {
    if (searchText) {
      const lowerSearchText = searchText.toLowerCase();
      const filtered = categories.filter(category => 
        category.name.toLowerCase().includes(lowerSearchText) ||
        category.description.toLowerCase().includes(lowerSearchText)
      );
      setFilteredCategories(filtered);
    } else {
      // 按排序顺序显示
      const sorted = [...categories].sort((a, b) => a.sortOrder - b.sortOrder);
      setFilteredCategories(sorted);
    }
  }, [categories, searchText]);

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchText(value);
  };

  // 处理添加分类
  const handleAddCategory = () => {
    setCurrentCategory(null);
    form.resetFields();
    // 设置默认排序为最后一位
    form.setFieldsValue({ 
      sortOrder: categories.length + 1,
      isActive: true 
    });
    setIsModalVisible(true);
  };

  // 处理编辑分类
  const handleEditCategory = (category: Category) => {
    setCurrentCategory(category);
    form.setFieldsValue({
      name: category.name,
      description: category.description,
      sortOrder: category.sortOrder,
      isActive: category.isActive
    });
    setIsModalVisible(true);
  };

  // 处理保存分类
  const handleSaveCategory = async () => {
    try {
      const values = await form.validateFields();
      if (currentCategory) {
        // 编辑现有分类
        await categoryService.updateCategory(currentCategory.id, {
          name: values.name,
          description: values.description,
          sort: values.sortOrder,
          isActive: values.isActive ? 1 : 0
        });
        message.success('分类更新成功');
      } else {
        // 添加新分类
        await categoryService.createCategory({
          name: values.name,
          description: values.description,
          sort: values.sortOrder,
          isActive: values.isActive ? 1 : 0
        });
        message.success('分类添加成功');
      }
      setIsModalVisible(false);
      form.resetFields();
      setCurrentCategory(null);
      // 重新加载数据
      fetchCategories();
    } catch (error: any) {
      console.error('保存分类失败:', error);
      message.error(error?.message || '保存分类失败');
    }
  };

  // 处理删除分类
  const handleDeleteCategory = async (id: number) => {
    const category = categories.find(c => c.id === id);
    if (category && category.articleCount > 0) {
      message.error('该分类下有文章，无法删除');
      return;
    }
    
    try {
      await categoryService.deleteCategory(id);
      message.success('分类删除成功');
      // 重新加载数据
      fetchCategories();
    } catch (error: any) {
      console.error('删除分类失败:', error);
      message.error(error?.message || '删除分类失败');
    }
  };

  // 处理排序上移
  const handleMoveUp = (id: number) => {
    const category = categories.find(c => c.id === id);
    if (!category || category.sortOrder === 1) return;
    
    // 找到上一个分类
    const prevCategory = categories.find(c => c.sortOrder === category.sortOrder - 1);
    if (!prevCategory) return;
    
    // 交换排序
    const updatedCategories = categories.map(c => {
      if (c.id === category.id) return { ...c, sortOrder: c.sortOrder - 1 };
      if (c.id === prevCategory.id) return { ...c, sortOrder: c.sortOrder + 1 };
      return c;
    });
    
    setCategories(updatedCategories);
    message.success('分类排序已更新');
  };

  // 处理排序下移
  const handleMoveDown = (id: number) => {
    const category = categories.find(c => c.id === id);
    if (!category || category.sortOrder === categories.length) return;
    
    // 找到下一个分类
    const nextCategory = categories.find(c => c.sortOrder === category.sortOrder + 1);
    if (!nextCategory) return;
    
    // 交换排序
    const updatedCategories = categories.map(c => {
      if (c.id === category.id) return { ...c, sortOrder: c.sortOrder + 1 };
      if (c.id === nextCategory.id) return { ...c, sortOrder: c.sortOrder - 1 };
      return c;
    });
    
    setCategories(updatedCategories);
    message.success('分类排序已更新');
  };

  // 切换分类状态
  const handleToggleActive = async (id: number, currentStatus: number) => {
    try {
      await categoryService.updateCategoryStatus(id, currentStatus ? 0 : 1);
      message.success('分类状态已更新');
      // 重新加载数据
      fetchCategories();
    } catch (error: any) {
      console.error('更新分类状态失败:', error);
      message.error(error?.message || '更新分类状态失败');
    }
  };

  // 计算总文章数
  const totalArticles = categories.reduce((sum, category) => sum + category.articleCount, 0);

  // 分类列表列配置
  const columns: ColumnsType<Category> = [
    {
      title: '排序',
      dataIndex: 'sortOrder',
      key: 'sortOrder',
      width: 80,
      render: (order: number) => (
        <Tag color="blue">{order}</Tag>
      )
    },
    {
      title: '分类名称',
      dataIndex: 'name',
      key: 'name',
      render: (name: string, record: Category) => (
        <div>
          <strong>{name}</strong>
          {!record.isActive && <Tag color="default" style={{ marginLeft: '8px' }}>已禁用</Tag>}
        </div>
      )
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true
    },
    {
      title: '文章数量',
      dataIndex: 'articleCount',
      key: 'articleCount',
      width: 100,
      align: 'center',
      render: (count: number) => (
        <Text type="success"><strong>{count}</strong></Text>
      )
    },
    {
      title: '占比',
      key: 'percentage',
      width: 150,
      render: (_, record: Category) => {
        const percentage = totalArticles > 0 ? (record.articleCount / totalArticles) * 100 : 0;
        return (
          <Progress percent={percentage} size="small" />
        );
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 120,
      render: (time: string) => new Date(time).toLocaleDateString()
    },
    {
      title: '操作',
      key: 'action',
      width: 250,
      render: (_, record: Category) => (
        <Space size="middle">
          <Button
            size="small"
            icon={<ArrowUpOutlined />}
            onClick={() => handleMoveUp(record.id)}
            disabled={record.sortOrder === 1}
          >
            上移
          </Button>
          <Button
            size="small"
            icon={<ArrowDownOutlined />}
            onClick={() => handleMoveDown(record.id)}
            disabled={record.sortOrder === categories.length}
          >
            下移
          </Button>
          <Button size="small" icon={<EditOutlined />} onClick={() => handleEditCategory(record)}>
            编辑
          </Button>
          <Button
            size="small"
            onClick={() => handleToggleActive(record.id, record.isActive)}
            type={record.isActive ? 'default' : 'primary'}
          >
            {record.isActive ? '禁用' : '启用'}
          </Button>
          <Popconfirm
            title="确定要删除此分类吗?"
            icon={<ExclamationCircleOutlined />}
            onConfirm={() => handleDeleteCategory(record.id)}
            okText="确定"
            cancelText="取消"
            disabled={record.articleCount > 0}
          >
            <Button size="small" danger icon={<DeleteOutlined />} disabled={record.articleCount > 0}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  // 分类统计数据
  const topCategories = [...categories]
    .sort((a, b) => b.articleCount - a.articleCount)
    .slice(0, 5);

  return (
    <div style={{ padding: '20px' }}>
      <Title level={3}>分类管理</Title>
      
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        {/* 分类统计卡片 */}
        <Col span={8}>
          <Card title="分类统计概览" bordered={true}>
            <div style={{ marginBottom: '16px' }}>
              <p>总分类数: <Text strong>{categories.length}</Text></p>
              <p>总文章数: <Text strong>{totalArticles}</Text></p>
              <p>平均每分类文章数: <Text strong>{totalArticles > 0 ? Math.round(totalArticles / categories.length) : 0}</Text></p>
            </div>
            
            <Divider style={{ margin: '12px 0' }} />
            
            <Title level={5}>热门分类 TOP 5</Title>
            <List
              dataSource={topCategories}
              renderItem={item => (
                <List.Item>
                  <List.Item.Meta
                    title={
                      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <span>{item.name}</span>
                        <Tag color="green">{item.articleCount} 篇</Tag>
                      </div>
                    }
                    description={
                      <Progress 
                        percent={totalArticles > 0 ? (item.articleCount / totalArticles) * 100 : 0} 
                        size="small" 
                        showInfo={false}
                      />
                    }
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>
        
        {/* 分类列表 */}
        <Col span={16}>
          <Card 
            title="分类列表"
            extra={
              <div style={{ display: 'flex', gap: '8px' }}>
                <Search
                  placeholder="搜索分类名称或描述"
                  allowClear
                  onSearch={handleSearch}
                  style={{ width: 250 }}
                />
                <Button type="primary" icon={<PlusOutlined />} onClick={handleAddCategory}>
                  添加分类
                </Button>
              </div>
            }
          >
            <Table
              columns={columns}
              dataSource={filteredCategories}
              rowKey="id"
              loading={loading}
              pagination={{ pageSize: 10 }}
              scroll={{ x: 1200 }}
            />
          </Card>
        </Col>
      </Row>

      {/* 分类编辑/添加模态框 */}
      <Modal
        title={currentCategory ? '编辑分类' : '添加分类'}
        open={isModalVisible}
        onOk={handleSaveCategory}
        onCancel={() => {
          setIsModalVisible(false);
          form.resetFields();
          setCurrentCategory(null);
        }}
        okText="保存"
        cancelText="取消"
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            label="分类名称"
            name="name"
            rules={[{ required: true, message: '请输入分类名称' }, { min: 2, max: 50, message: '分类名称长度应在 2-50 个字符之间' }]}
          >
            <Input placeholder="请输入分类名称" />
          </Form.Item>
          
          <Form.Item
            label="分类描述"
            name="description"
            rules={[{ max: 200, message: '分类描述长度不能超过 200 个字符' }]}
          >
            <Input.TextArea placeholder="请输入分类描述" rows={3} />
          </Form.Item>
          
          <Form.Item
            label="排序顺序"
            name="sortOrder"
            rules={[{ required: true, message: '请输入排序顺序' }, { type: 'number', min: 1, message: '排序顺序必须为大于 0 的整数' }]}
          >
            <InputNumber style={{ width: '100%' }} placeholder="请输入排序顺序" />
          </Form.Item>
          
          <Form.Item
            label="状态"
            name="isActive"
            valuePropName="checked"
          >
            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default CategoryManagement;
